package com.hadoop.mapreduce;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
/**
 * 数据排序
 * @date 2015年5月7日 下午5:02:16
 * @author zhouxiao
 */
public class WordSort {
	//map
	public static class TokenizerMapper extends Mapper<Object, Text, LongWritable, IntWritable> {
		public void map(Object key, LongWritable value,Context context)throws IOException, InterruptedException {
			context.write(value, new IntWritable(1));
		}
	}
	//reduce
	public static class IntSumReducer extends Reducer<IntWritable, IntWritable, IntWritable,IntWritable>{
		private static IntWritable linenum=new IntWritable(1);
		public void reduce(IntWritable key, Iterable<IntWritable> values,Context context)throws IOException, InterruptedException {
				for (IntWritable intWritable : values) {
					context.write(linenum, key);
					linenum=new IntWritable(linenum.get()+1);
				}
		}
		
	}
	//排序
	public static class Partition extends Partitioner<LongWritable,IntWritable>{

		public int getPartition(LongWritable key, IntWritable value,int paramInt) {
			System.out.println("key="+key.get()+",value="+value+",param="+paramInt);
			int Maxnum=65223;
			int bound=Maxnum/paramInt+1;
			for (int i = 0; i < paramInt; i++) {
				if(key.get()<bound*i && key.get()>=bound*(i-1)){
					return i-1;
				}
				return -1;
			}
			return 0;
		}
		
	}
	 public static void main(String[] args) throws Exception {
		 	String paths="hdfs://master:9000//usr//local//tmp/test//in1.txt,hdfs://master:9000//usr//local//tmp/test//in2.txt";
		    Configuration conf = new Configuration();
		    Job job = new Job(conf, "word uniq");
		    job.setJarByClass(WordSort.class);
		    job.setMapperClass(TokenizerMapper.class);
		    job.setCombinerClass(IntSumReducer.class);
		    job.setReducerClass(IntSumReducer.class);
		    job.setPartitionerClass(Partition.class);
		    job.setOutputKeyClass(Text.class);
		    job.setOutputValueClass(Text.class);
		    FileInputFormat.addInputPaths(job,paths);
		    FileOutputFormat.setOutputPath(job, new Path("hdfs://master:9000//usr//local//tmp/test//out"));
		    System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
